package com.example.lianjuan.Presenter.impl.impl;

import com.example.lianjuan.Model.API;
import com.example.lianjuan.Model.domain.HomePagerCategories;
import com.example.lianjuan.Presenter.impl.ICategoryPagerPresenter;
import com.example.lianjuan.Utils.LogUtils;
import com.example.lianjuan.Utils.RetrofitManang;
import com.example.lianjuan.Utils.UtilsUrl;
import com.example.lianjuan.View.ICategoryPagerCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 首页分类网络请求
 *
 * @author 81067
 */
public class CategoryPagerPresenterImpl implements ICategoryPagerPresenter {
    private Map<Integer, Integer> pagesInfo = new HashMap<>();
    private static final Integer DEFAULT_PAGE = 1;
    private Integer mInteger;
    private Integer mCurrentPage;
    private List<ICategoryPagerCallback> mICategoryPagerCallback = new ArrayList<>();

    @Override
    public void getContentByCategoriesId(int CategoriesId) {
        for (ICategoryPagerCallback iCategoryPagerCallback : mICategoryPagerCallback) {
            if (iCategoryPagerCallback.getCategoryId() == CategoriesId) {
                iCategoryPagerCallback.onLoadLoading();
            }
        }
        for (ICategoryPagerCallback iCategoryPagerCallback : mICategoryPagerCallback) {
            if (iCategoryPagerCallback.getCategoryId() == CategoriesId) {
                mInteger = pagesInfo.get(CategoriesId);
                if (mInteger == null) {
                    mInteger = DEFAULT_PAGE;
                    pagesInfo.put(CategoriesId, mInteger);
                }
                Call<HomePagerCategories> pagerCaCategories = createTask(CategoriesId, mInteger);
                pagerCaCategories.enqueue(new Callback<HomePagerCategories>() {
                    @Override
                    public void onResponse(Call<HomePagerCategories> call, Response<HomePagerCategories> response) {
                        int code = response.code();
                        if (code == HttpURLConnection.HTTP_OK) {
                            HomePagerCategories pagerContent = response.body();
                            LogUtils.d(CategoryPagerPresenterImpl.this, "------>" + pagerContent.toString());
                            //正常的更新UI
                            handleHomePagerContentResult(pagerContent, CategoriesId);
                        } else {
                            //网路错误的加载
                            handleNetworkError(CategoriesId);
                        }
                    }

                    @Override
                    public void onFailure(Call<HomePagerCategories> call, Throwable t) {
                        handleNetworkError(CategoriesId);
                        LogUtils.d(CategoryPagerPresenterImpl.this, t.toString());
                    }
                });
            }
        }
    }

    private Call<HomePagerCategories> createTask(int CategoriesId, Integer integer) {
        Retrofit retrofit = RetrofitManang.getRetrofitManang().getRetrofit();
        API api = retrofit.create(API.class);
        Call<HomePagerCategories> task = api.getPagerCaCategories(UtilsUrl.getCategoriesUrl(CategoriesId, integer));
        return task;
    }

    private void handleNetworkError(int CategoriesId) {
        for (ICategoryPagerCallback iCategoryPagerCallback : mICategoryPagerCallback) {
            if (iCategoryPagerCallback.getCategoryId() == CategoriesId) {
                iCategoryPagerCallback.onNetworkError();
            }
        }
    }

    private void handleHomePagerContentResult(HomePagerCategories pagerContent, int CategoriesId) {
        List<HomePagerCategories.DataDTO> data = pagerContent.getData();
        //通知UI更新数据
        for (ICategoryPagerCallback iCategoryPagerCallback : mICategoryPagerCallback) {
            if (iCategoryPagerCallback.getCategoryId() == CategoriesId) {
                if (pagerContent.getData().size() == 0 || pagerContent == null) {
                    iCategoryPagerCallback.onLoadEmpty();
                } else {
                    //轮播图数据，取数据最后五个
                    List<HomePagerCategories.DataDTO> looperData = data.subList(data.size() - 5, data.size());
                    iCategoryPagerCallback.onLooperListMoreLoaded(looperData);
                    //商品列表数据
                    iCategoryPagerCallback.onCategoriseLoaded(pagerContent.getData());
                }
            }
        }
    }

    ;

    //加载更多数据
    @Override
    public void onLoadMore(int CategoriesId) {
        LogUtils.d(CategoryPagerPresenterImpl.this, "result --->");
        //1.获取当前页码
        mCurrentPage = pagesInfo.get(CategoriesId);
        if (mCurrentPage == null) {
            mCurrentPage = DEFAULT_PAGE;
        }
        //2.页码++
        mCurrentPage++;
        //3.加载数据
        Call<HomePagerCategories> task = createTask(CategoriesId, mCurrentPage);
        task.enqueue(new Callback<HomePagerCategories>() {
            @Override
            public void onResponse(Call<HomePagerCategories> call, Response<HomePagerCategories> response) {
                //请求成功
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerCategories result = response.body();
                    LogUtils.d(CategoryPagerPresenterImpl.this, "result --->" + result);
                    handleLoaderResult(result, CategoriesId);
                } else {
                    handLoadMoreError(CategoriesId);
                    LogUtils.d(CategoryPagerPresenterImpl.this, "网络请求失败");
                }
            }

            @Override
            public void onFailure(Call<HomePagerCategories> call, Throwable t) {
                //请求失败
                LogUtils.d(CategoryPagerPresenterImpl.this, t.toString());
                handLoadMoreError(CategoriesId);
            }
        });


    }

    private void handleLoaderResult(HomePagerCategories result, Integer CategoriesId) {
        for (ICategoryPagerCallback iCategoryPagerCallback : mICategoryPagerCallback) {
            if (iCategoryPagerCallback.getCategoryId() == CategoriesId) {
                if (CategoriesId == null || result.getData().size() == 0) {
                    iCategoryPagerCallback.onLoaderMoreEmpty();
                } else {
                    LogUtils.d(this, "更多资源正在加载");
                    iCategoryPagerCallback.onLoaderMoreLoaded(result.getData());
                }
            }
        }
    }

    private void handLoadMoreError(Integer CategoriesId) {
        mCurrentPage--;
        pagesInfo.put(CategoriesId, mCurrentPage);
        for (ICategoryPagerCallback iCategoryPagerCallback : mICategoryPagerCallback) {
            if (iCategoryPagerCallback.getCategoryId() == CategoriesId) {
                iCategoryPagerCallback.onLoaderMoreNetworkError();
            }
        }
    }

    //刷新数据
    @Override
    public void reload(int CategoriesId) {
        if (mCurrentPage == null) {
            mCurrentPage = DEFAULT_PAGE;
        } else {
            mCurrentPage++;
        }
        Call<HomePagerCategories> task = createTask(CategoriesId, mCurrentPage);
        task.enqueue(new Callback<HomePagerCategories>() {
            @Override
            public void onResponse(Call<HomePagerCategories> call, Response<HomePagerCategories> response) {
                //请求成功
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerCategories result = response.body();
                    LogUtils.d(CategoryPagerPresenterImpl.this, "result --->" + result);
                    //handleLoaderResult(result, CategoriesId);
                } else {
                    handLoadMoreError(CategoriesId);
                    LogUtils.d(CategoryPagerPresenterImpl.this, "网络请求失败");
                }
            }

            @Override
            public void onFailure(Call<HomePagerCategories> call, Throwable t) {
                //请求失败
                LogUtils.d(CategoryPagerPresenterImpl.this, t.toString());
                handLoadMoreError(CategoriesId);
            }
        });
    }

    @Override
    public void registerViewCallback(ICategoryPagerCallback callback) {
        if (!mICategoryPagerCallback.contains(callback)) {
            mICategoryPagerCallback.add(callback);
        }
    }

    @Override
    public void unregisterViewCallback(ICategoryPagerCallback callback) {
        mICategoryPagerCallback.remove(callback);
    }
}
